package com.example.webapp.web.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.example.webapp.hibernate.HibernateManager;
import com.example.webapp.hibernate.user.User;

public class UserDetailsServiceImpl implements UserDetailsService {
	
	private HibernateManager hibernateManager;
	
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		
		Session session = hibernateManager.createSession();
		session.beginTransaction();
		
		User user = (User) session.get(User.class, username);
		
		if (user != null) {
			return new UserDetailsImpl(user);
		}
		
		return null;
	}
	
	private class UserDetailsImpl implements UserDetails {

		private static final long serialVersionUID = 7396655390496839945L;
		private final User user;
		
		public UserDetailsImpl(User user) {
			this.user = user;
		}
		
		public Collection<GrantedAuthority> getAuthorities() {
			List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
			
			for (String s : user.getRoles().split(",")) {
				authorities.add(new GrantedAuthorityImpl(s.trim()));
			}
			
			return authorities;
		}

		public String getPassword() {
			return user.getPassword();
		}

		public String getUsername() {
			return user.getUsername();
		}

		public boolean isAccountNonExpired() {
			// TODO Auto-generated method stub
			return true;
		}

		public boolean isAccountNonLocked() {
			// TODO Auto-generated method stub
			return true;
		}

		public boolean isCredentialsNonExpired() {
			// TODO Auto-generated method stub
			return true;
		}

		public boolean isEnabled() {
			// TODO Auto-generated method stub
			return true;
		}
	}
	
	public void setHibernateManager(HibernateManager hibernateManager) {
		this.hibernateManager = hibernateManager;
	}
}
